import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from "@/views/LoginView.vue";
import HomeView from "@/views/HomeView.vue";
import HelloView from "@/views/HelloView.vue";
// 导入store，查看store中是否存在username来判断是否登录
import store  from "@/store";
// 导入element-ui的Message组件
import {Message} from "element-ui";
import UserView from "@/views/UserView.vue";
import LLLView from "@/views/LLLView.vue";

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'login',
    component: LoginView
  },{
    path: '/home',
    name: 'home',
    component: HomeView,
    children:[
        {
          path: '',
          name: 'hello',
          component: HelloView
        },
      {
        path: 'user',
        name: 'user',
        component: UserView
      },
      {
        path: 'lll',
        name: 'lll',
        component:LLLView
      }
    ]
  },

]

const router = new VueRouter({
  routes
})
// 路由守卫
router.beforeEach((to, from, next) => {
  // 如果不是登录页面，并且store中不存在username，则跳转到登录页面
  if(to.name !== "login" && store.state.username === ''){
    // 提示用户需要登录
    Message.error("请先登录");
    // 跳转到登录页面
    next({name: 'login'})

  }else {
    // 如果已登陆，则直接放行
    next()
  }
})

export default router
